import {
  reqAddHospitalSet,
  reqGetHospitalSetItem,
  reqUpdateHospitalSet,
} from "@/api/hospital/hospitalSet/hospitalSet";
import { Button, Card, Form, Input, message, Space } from "antd";
import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";

export default function AddOrUpdateHospitalSet() {
  //声明状态
  let [loading, setLoading] = useState<boolean>(false);
  //创建 form 对象
  const [form] = Form.useForm();
  //获取 url 中的 id 参数
  let { id } = useParams();

  //声明事件回调
  const finish = async () => {
    //获取表单元素的值
    let fields = form.getFieldsValue();
    //修改状态为加载中
    setLoading(true);
    try {
      //判断
      if (!id) {
        //发送请求 新增数据
        await reqAddHospitalSet(fields);
        //新增提示
        message.success("新增成功");
      } else {
        //更新数据
        await reqUpdateHospitalSet({...fields, id});
        message.success('更新成功');
      }
      //修改为未加载中
      setLoading(false);
    } catch (e) {
      setLoading(false);
    }
  };

  //组件挂载完毕
  useEffect(() => {
    //发送请求  reqGetHospitalSetItem
    let getHospital = async () => {
      //如果 id 有值, 表明是更新, 则发送请求, 反之则不发送请求
      if (id) {
        //发送请求
        let result = await reqGetHospitalSetItem(id as string);
        //将结果在组件中进行渲染
        form.setFieldsValue(result);
      }
    };

    getHospital();
  }, []);

  return (
    <Card>
      <Form form={form} labelCol={{ span: 2 }} onFinish={finish}>
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: "请输入医院名称" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: "请输入医院编号" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="API基础路径"
          name="apiUrl"
          rules={[{ required: true, message: "请输入API基础路径" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: "请输入联系人姓名" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[
            { required: true, message: "请输入联系人手机" },
            { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确" },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 2, span: 16 }}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              {id ? '更新' : '保存'}
            </Button>
            <Link to="/syt/hospital/hospitalSet">
              <Button>返回</Button>
            </Link>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}
